<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column label="展开" type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="index1"
              :class="[index1 == 0 ? 'bdtop' : '', 'bdbottom', 'center']"
            >
              <el-col :span="4">
                <el-tag type="primary" closable size="medium" @close="deleteRights(scope.row, item1.id)">{{item1.authName}}</el-tag>
              </el-col>
              <el-col :span="20">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="index2"
                  :class="[index2 != 0 ? 'bdtop' : '', 'center']"
                >
                  <el-col :span="4">
                    <el-tag type="warning" closable size="medium"  @close="deleteRights(scope.row, item2.id)">{{item2.authName}}</el-tag>
                  </el-col>
                  <el-col :span="20">
                    <el-tag
                      type="danger"
                      closable
                      size="medium"
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      @close="deleteRights(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="level">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeRole(scope.row.id)"
            ></el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-star-off"
              @click="showAllotDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- ----------------------- -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="30%" @close="addDialogClose">
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- ---------------------------------- -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="30%">
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="addRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- -------------------------- -->
    <el-dialog
      title="分配权限"
      :visible.sync="allotDialogVisible"
      width="30%"
      @close="allotDialogClose"
    >
      <el-tree
        :props="props"
        show-checkbox
        ref="treeRef"
        :data="rightsTree"
        default-expand-all
        node-key="id"
        :default-checked-keys="selectedKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      allotDialogVisible: false,
      addForm: {},
      editForm: {},
      rightsTree: [],
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请选择角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      },
      props: {
        label: 'authName',
        children: 'children'
      },
      selectedKeys: [],
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      console.log(res)
    },
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('失败')
        this.getRoleList()
        this.$message.success('成功')
        this.addDialogVisible = false
      })
    },
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    async removeRole (id) {
      this.$confirm('确定永久删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('roles/' + id)
          if (res.meta.status !== 200) return this.$message.error('失败')
          this.getRoleList()
          this.$message.success('成功')
        })
        .catch(() => {
          this.$message.info('取消')
        })
    },
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('失败')
      this.editForm = res.data
      this.$message.success('成功')
    },
    editRole () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        )
        if (res.meta.status !== 200) return this.$message.error('失败')
        this.getRoleList()
        this.$message.success('成功')
        this.editDialogVisible = false
      })
    },
    async showAllotDialog (row) {
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res.data)
      this.rightsTree = res.data
      this.setKeys(row, this.selectedKeys)
      this.roleId = row.id
      this.allotDialogVisible = true
    },
    allotDialogClose () {
      this.selectedKeys = []
      this.roleId = ''
    },
    async allotRights () {
      this.allotDialogVisible = false
      this.selectedKeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: this.selectedKeys.join(',')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('失败')
      this.getRoleList()
      this.$message.success('成功')
    },
    setKeys (data, arr) {
      if (!data.children) return arr.push(data.id)
      data.children.forEach(item => {
        this.setKeys(item, arr)
      })
    },
    async deleteRights (data, id) {
      const { data: res } = await this.$http.delete(`roles/${data.id}/rights/${id}`)
      if (res.meta.status !== 200) return this.$message.error('失败')
      data.children = res.data
      console.log(res.data)
      this.$message.success('成功')
    }
  }
}
</script>

<style scoped lang="less">
.el-breadcrumb {
  font-size: 12px;
}
.el-card {
  margin-top: 15px;

  .el-table {
    margin-top: 15px;
  }
}
.bdtop {
  border-top: 1px solid #ccc;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
.center {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 10px;
}
</style>
